package com.mavenq.fly;

import com.mavenq.fly.business.service.DataConsumerService;
import com.mavenq.fly.business.service.DataProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.annotation.PreDestroy;

@SpringBootApplication
@EnableAsync
@Slf4j
public class FlySpringBootApplication implements CommandLineRunner {

    @Autowired
    private  DataProducerService producerService;
    @Autowired
    private  DataConsumerService consumerService;
    @Value("${queue.mode.enabled:false}")
    private String isEnableQueue;


    public static void main(String[] args) {
        SpringApplication.run(FlySpringBootApplication.class, args);
        log.info("=========================应用启动完成========================");
    }

    @Override
    public void run(String... args) throws Exception {
        if(StringUtils.equals(isEnableQueue,"true")){
            // 启动前重置所有PROCESSING状态记录
            producerService.resetProcessingOnShutdown();

            // 启动生产者和消费者
            producerService.start();
            consumerService.start();

            log.info("Producer-Consumer application started");
        }
    }

    @PreDestroy
    public void onShutdown() {
        if(StringUtils.equals(isEnableQueue,"true")){
            log.info("Application shutdown initiated");
            producerService.stop();
            consumerService.stop();
            log.info("Application shutdown completed");
        }
    }

//    @Bean
//    public CommandLineRunner dataInitializer() {
//        return args -> {
//            // 可以在这里初始化测试数据
//            log.info("Application initialized");
//        };
//    }
}
